import { storeToRefs } from "pinia";
import useVoiceTaskStore from "../store/useVoiceTaskStore";
import { useReminderStore } from "../store/reminderStore";

// WebSocket 工具类，封装了 WebSocket 的连接、发送、接收、心跳、重连和关闭等操作
class WebSocketUtil {
  // WebSocket 服务器的 URL
  url: string;
  // 心跳发送的间隔时间（秒）
  time: number;
  // WebSocket 任务对象
  socketTask: any;
  // WebSocket 连接是否打开
  isOpen: boolean;
  // 重连定时器
  reconnectTimeout: number | undefined;
  // 心跳定时器
  heartbeatInterval: number | undefined;
  // 存储外部注册的消息回调函数的数组
  messageCallbacks: Array<(data: string) => void>;
  storeCode:string;
  terminalId:string;
  terminalType:string;
  merchantCode?:string;

  // 构造函数，初始化 WebSocket 连接
  constructor(url: string, time: number, storeCode:string, terminalId:string, terminalType:string, merchantCode?:string) {
    this.url = url;
    this.time = time;
    this.socketTask = null;
    this.isOpen = false;
    this.reconnectTimeout = undefined;
    this.heartbeatInterval = undefined;
    this.messageCallbacks = [];
    this.storeCode = storeCode;
    this.terminalId = terminalId;
    this.terminalType = terminalType;
    this.merchantCode = merchantCode;

    // 初始化 WebSocket 连接
    this.initializeWebSocket();
  }

  // 初始化 WebSocket 连接
  initializeWebSocket() {
    const voiceTaskStore = useVoiceTaskStore();
    const reminderStore = useReminderStore();
    const { remindType, voiceStyle } = storeToRefs(reminderStore);
    // console.log(voiceTaskStore, remindType, voiceStyle, 'voiceTaskStore, remindType, voiceStyle')
    this.socketTask = uni.connectSocket({
      url: this.url,
      complete: (res) => {
        console.log('WebSocket连接中',this.url, this.time, res);
      }
    });

    this.socketTask.onOpen((result: any) => {
      console.log("WebSocket连接成功", this.url, this.time, result);
      this.send(JSON.stringify({ storeCode: this.storeCode, terminalType: this.terminalType, terminalId: this.terminalId, merchantCode: this.merchantCode }));
      this.isOpen = true;
      // 连接成功后启动心跳和消息监听
      this.startHeartbeat();
      this.listenForMessages();
    });

    // 注意：这里的 onClose 监听器应该放在 uni.connectSocket 调用之后
    this.socketTask.onClose((result: any) => {
      console.error('WebSocket连接已关闭', result);
      this.isOpen = false;
      if(result?.code !== 1005){
        this.reconnect();
      }
    });
    // 注意：这里的 onError 监听器应该放在 uni.connectSocket 调用之后
    this.socketTask.onError((error: any) => {
      console.error('WebSocket连接失败', this.url, this.time, error);
      voiceTaskStore.addVoiceTask({
        id: new Date().getTime(),
        remindType: remindType.value,
        path: 'static/audio/' + voiceStyle.value + '/' + 'network_connect_exception.mp3',
        times: 1
      })
      this.reconnect();
    });
  }

  // 启动心跳检测
  startHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
    }
    console.log("WebSocket startHeartbeat",this.time, this.heartbeatInterval);
    this.heartbeatInterval = setInterval(() => {
      if (this.isOpen) {
        this.send('ping');
      }
    }, this.time * 1000);
  }
  //切换门店
  switchStore(storeCode: string) {
    this.storeCode = storeCode;
    this.send(JSON.stringify({storeCode: this.storeCode, terminalType: this.terminalType, terminalId: this.terminalId}));
  }

  switchMerchantCode(merchantCode: string) {
    this.merchantCode = merchantCode;
    this.send(JSON.stringify({ storeCode: this.storeCode, terminalType: this.terminalType, terminalId: this.terminalId, merchantCode: this.merchantCode }));
  }
  // 发送消息
  send(data: string) {
    console.log("WebSocket send",this.isOpen, data, this.socketTask?.readyState);
    if (this.socketTask) {
      this.socketTask.send({
        data: data,
        success: (res: any) => {
          console.log('消息发送成功', res);
        },
        fail: (error: any) => {
          console.error('消息发送失败', error);
          this.reconnect(); // 这里可能需要根据实际情况判断是否重连
        }
      });
    }
  }

  onOpen(callback: (data: string) => void){
    console.log('onOpen:this.socketTask', this.socketTask);

    if (this.socketTask) {
      this.socketTask.onOpen((res: any) => {
        callback
      });
    } else {
      console.error('WebSocket 连接尚未建立，无法监听消息');
    }
  }

  // 监听 WebSocket 消息
  listenForMessages() {
    console.log('listenForMessages this.socketTask:', this.socketTask);
    if (this.socketTask) {
      this.socketTask.onMessage((res: { data: any }) => {
        console.log('listenForMessages data:', res);
        const { data } = res;
        this.messageCallbacks.forEach(callback => callback(data.toString())); // 假设 data 是字符串或可转换为字符串
      });
    } else {
      console.error('WebSocket 连接尚未建立，无法监听消息');
    }
  }

  // 重连 WebSocket
  reconnect() {
    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
    }
    this.reconnectTimeout = setTimeout(() => {
      this.initializeWebSocket();
    }, 3000);
  }

  // 关闭 WebSocket 连接
  closeSocket() {
    if (this.socketTask) {
      uni.closeSocket({
        success: () => {
          console.log('WebSocket连接已关闭');
          this.isOpen = false;
        },
        fail: (error) => {
          console.error('关闭WebSocket连接失败', error);
        }
      });
      this.socketTask = null;
    }
  }

  // 外部注册消息回调函数
  onMessage(callback: (data: string) => void) {
    this.messageCallbacks.push(callback);
  }

  // 外部注销消息回调函数
  offMessage(callback: (data: string) => void) {
    this.messageCallbacks = this.messageCallbacks.filter(cb => cb !== callback);
  }

  // 销毁 WebSocket 连接，清理资源
  destroy() {
    this.closeSocket();
    clearInterval(this.heartbeatInterval);
    clearTimeout(this.reconnectTimeout);
    this.messageCallbacks = [];
  }
}

export default WebSocketUtil;
